package com.itdl.controller;

import com.itdl.dto.fastdfs.UploadResponseDTO;
import com.itdl.file.IFileOperator;
import com.itdl.util.DownloadUtil;
import com.itdl.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @author: itdl
 * @date: 2022/3/7 14:33
 * @description: 文件操作接口类
 * @version: 1.0
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @Autowired
    private IFileOperator fileOperator;

    @PostMapping("/upload")
    public R<UploadResponseDTO> upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (file == null){
            return R.error("501", "文件不能为空");
        }
        // 执行文件上传
        UploadResponseDTO upload = fileOperator.upload(file.getBytes(), file.getSize(), file.getOriginalFilename());

        if (upload == null){
            return R.error("500", "文件上传出现异常");
        }
        return R.success(upload);
    }


    @RequestMapping(value = "/download", method = {RequestMethod.GET, RequestMethod.POST})
    public void download(@RequestParam("fileId") String fileId, HttpServletResponse response){
        // 下载为字节数组
        byte[] bytes = fileOperator.download(fileId);
        // 下载到流中
        DownloadUtil.download(response, bytes, "fastdfs图片"  + System.currentTimeMillis() + UUID.randomUUID().toString().replaceAll("-", "") );
    }
}
